<template>
  <el-dialog
      :model-value="modelValue"
      title="可视化设置"
      width="600px"
      @update:modelValue="closeDialog"
      @open="initializeLocalSettings"
      :close-on-click-modal="false"
      draggable
      top="10vh"
      class="settings-dialog"
  >
    <el-tabs v-model="activeTab" class="settings-tabs">
      <!-- Layout Tab -->
      <el-tab-pane label="布局" name="layout">
        <el-form label-position="right" label-width="120px">
          <el-form-item label="布局方向">
            <el-tooltip placement="top" content="设置节点层级的排列方向">
              <el-radio-group v-model="localSettings.layoutDirection">
                <el-radio value="TB">从上到下 (TB)</el-radio>
                <el-radio value="LR">从左到右 (LR)</el-radio>
              </el-radio-group>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="连接点位置">
            <el-tooltip placement="top" content="设置边的连接点位置 (Handle Position)">
              <el-radio-group v-model="localSettings.handlePositionMode">
                <el-radio value="auto">自适应布局方向</el-radio>
                <el-radio value="top-bottom">固定上下</el-radio>
                <el-radio value="left-right">固定左右</el-radio>
              </el-radio-group>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="同级节点间距">
            <el-tooltip placement="top" content="同一层级相邻节点的最小间距 (Dagre nodesep)">
              <el-slider v-model="localSettings.nodeSpacing" :min="10" :max="200" show-input />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="层级间距">
            <el-tooltip placement="top" content="相邻层级之间的最小间距 (Dagre ranksep)">
              <el-slider v-model="localSettings.layerSpacing" :min="10" :max="200" show-input />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="节点对齐">
            <el-tooltip placement="top" content="同一层级内节点的对齐方式 (Dagre align)">
              <el-select v-model="localSettings.dagreAlign" placeholder="默认 (UL)" clearable>
                <el-option label="左上 (UL)" value="UL" />
                <el-option label="右上 (UR)" value="UR" />
                <el-option label="左下 (DL)" value="DL" />
                <el-option label="右下 (DR)" value="DR" />
                <el-option label="居中 (C)" value="C" />
              </el-select>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="层级分配算法">
            <el-tooltip placement="top" content="计算节点层级的算法 (Dagre ranker)">
              <el-select v-model="localSettings.dagreRanker" placeholder="默认 (Network Simplex)">
                <el-option label="Network Simplex" value="network-simplex" />
                <el-option label="Tight Tree" value="tight-tree" />
                <el-option label="Longest Path" value="longest-path" />
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- Node Display Tab -->
      <el-tab-pane label="节点显示" name="nodeDisplay">
        <el-form label-position="right" label-width="120px">
          <el-form-item label="属性显示">
            <el-radio-group v-model="localSettings.attributeDisplayMode">
              <el-radio value="hide" label="hide">隐藏</el-radio>
              <el-radio value="count" label="count">仅显示数量</el-radio>
              <el-radio value="first-1" label="first-1">显示前 1 个</el-radio>
              <el-radio value="first-3" label="first-3">显示前 3 个</el-radio>
              <el-radio value="all" label="all">全部显示 (截断)</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="属性分隔线">
            <el-radio-group v-model="localSettings.attributeSeparatorStyle">
              <el-radio value="none" label="none">无</el-radio>
              <el-radio value="dashed" label="dashed">虚线</el-radio>
              <el-radio value="solid" label="solid">实线</el-radio>
              <el-radio value="dotted" label="dotted">点线</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="抹平外观差异">
            <el-switch v-model="localSettings.normalizeAppearanceWithAttrs" />
            <el-tooltip placement="top" content="尝试使有属性的节点（即使属性被隐藏）与无属性节点的视觉高度保持一致。" style="margin-left: 8px;">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>

          <!-- NEW: XML Tag Name Display Setting -->
          <el-divider />
          <el-form-item label="XML 标签名显示">
             <el-tooltip placement="top" content="选择如何显示 XML 元素的标签名 (仅对 XML 文档生效)">
               <el-radio-group v-model="localSettings.xmlTagNameDisplayMode">
                 <el-radio value="nameOnly">仅名称 (e.g., Media)</el-radio>
                 <el-radio value="openingTag">开始标签 (e.g., &lt;Media&gt;)</el-radio>
                 <el-radio value="closingTag">结束标签 (e.g., &lt;/Media&gt;)</el-radio>
               </el-radio-group>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- Coloring Tab -->
      <el-tab-pane label="节点着色" name="coloring">
        <el-form label-position="top">
          <el-form-item label="着色模式">
            <el-radio-group v-model="localSettings.coloringMode" class="coloring-mode-radio-group-flex">
              <!-- Structure Single Color -->
              <div class="radio-item-wrapper">
                <el-radio value="single-structure" label="single-structure">结构单色</el-radio>
                <el-color-picker
                    v-if="localSettings.coloringMode === 'single-structure'"
                    v-model="localSettings.singleStructureColorValue"
                    class="mode-color-picker" show-alpha
                />
              </div>
              <!-- True Single Color -->
              <div class="radio-item-wrapper">
                <el-radio value="single-true" label="single-true">完全单色</el-radio>
                <el-color-picker
                    v-if="localSettings.coloringMode === 'single-true'"
                    v-model="localSettings.trueSingleColorValue"
                    class="mode-color-picker" show-alpha
                />
              </div>
              <!-- Level -->
              <div class="radio-item-wrapper">
                <el-radio value="level" label="level">按层级</el-radio>
              </div>
              <!-- Semantic -->
              <div class="radio-item-wrapper">
                <el-radio value="semantic" label="semantic">语义类型</el-radio>
              </div>
              <!-- JDF Keyword Only -->
              <div class="radio-item-wrapper">
                <el-tooltip placement="top" content="仅高亮 JDF 核心标签，无层级颜色调整">
                  <el-radio value="jdf-keyword" label="jdf-keyword">仅 JDF 关键词</el-radio>
                </el-tooltip>
              </div>
              <!-- JDF Keyword + Level -->
              <div class="radio-item-wrapper">
                <el-tooltip placement="top" content="高亮 JDF 核心标签，并根据层级调整颜色 (默认)">
                  <el-radio value="jdf-keyword-level" label="jdf-keyword-level">JDF 关键词+层级</el-radio>
                </el-tooltip>
              </div>
              <!-- Metron Keyword (Disabled) -->
              <div class="radio-item-wrapper">
                <el-tooltip placement="top" content="高亮 Metron 关键词 (模糊匹配 - 待实现)">
                  <el-radio value="metron-keyword" label="metron-keyword" :disabled="true">仅 Metron 关键词</el-radio>
                </el-tooltip>
              </div>
              <!-- Metron Keyword + Level (Disabled) -->
              <div class="radio-item-wrapper">
                <el-tooltip placement="top" content="高亮 Metron 关键词并根据层级调整 (模糊匹配 - 待实现)">
                  <el-radio value="metron-keyword-level" label="metron-keyword-level" :disabled="true">Metron 关键词+层级</el-radio>
                </el-tooltip>
              </div>
              <!-- Custom Schema (Disabled) -->
              <div class="radio-item-wrapper">
                <el-tooltip placement="top" content="允许未来通过用户定义的规则进行着色 (待实现)">
                  <el-radio value="custom-schema" label="custom-schema" :disabled="true">用户自定义 Schema</el-radio>
                </el-tooltip>
              </div>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- Miscellaneous Tab -->
      <el-tab-pane label="Miscellaneous" name="misc">
        <el-form label-position="right" label-width="120px">
          <el-form-item label="节点渲染方式">
            <el-radio-group v-model="localSettings.nodeRenderingMethod">
              <el-radio value="template" label="template">模板 (Template)</el-radio>
              <el-radio value="renderFunction" label="renderFunction">渲染函数 (Render)</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <!-- NEW: XML Parser Selection -->
          <el-divider />
          <el-form-item label="XML 解析器 (通用)">
             <el-tooltip placement="top" content="选择用于通用视图的 XML 解析器 (影响初始加载)">
               <el-radio-group v-model="localSettings.selectedXmlParser">
                 <el-radio value="dom">浏览器 DOMParser (默认)</el-radio>
                 <el-radio value="fast-xml">fast-xml-parser</el-radio>
                 <el-radio value="libxml2">libxml2-wasm</el-radio>
               </el-radio-group>
            </el-tooltip>
          </el-form-item>

          <!-- NEW: Realtime XML Validation Switch -->
          <el-form-item label="Realtime XML Format Check">
            <el-switch v-model="localSettings.enableRealtimeXmlValidation" />
            <el-tooltip
                effect="dark"
                content="Enable basic XML format checking while typing (uses fast-xml-parser)."
                placement="top-start"
                style="margin-left: 8px;"
            >
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </el-form-item>

          <!-- NEW: Editor Word Wrap -->
          <el-form-item label="Editor Word Wrap">
            <el-switch v-model="localSettings.wordWrap" />
            <el-tooltip
                effect="dark"
                content="Enable word wrap in the editor"
                placement="top-start"
                style="margin-left: 8px;"
            >
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </el-form-item>

          <!-- NEW: Script Parser Engine -->
          <el-form-item label="Script Parser Engine">
            <el-radio-group v-model="localSettings.scriptParserEngine">
              <el-radio-button label="swc">SWC (Faster)</el-radio-button>
              <el-radio-button label="babel">Babel (More Features)</el-radio-button>
            </el-radio-group>
            <el-tooltip content="Choose the engine for parsing JavaScript/TypeScript. Babel enables more accurate QuickJS evaluation strings." placement="top">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- NEW QuickJS Tab -->
      <el-tab-pane label="QuickJS & Display" name="quickjs">
         <el-form label-position="right" label-width="180px">
           <el-form-item label="Enable Automatic Evaluation">
             <el-switch 
               v-model="localSettings.enableAutomaticQuickJs"
               inline-prompt
               style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
               active-text="On"
               inactive-text="Off"
             />
             <el-tooltip placement="top" content="Evaluate JavaScript/TypeScript default exports using QuickJS to display computed values in the visualizer.">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
             </el-tooltip>
          </el-form-item>

          <el-divider content-position="left">QuickJS 执行限制</el-divider>
          <el-form-item label="脚本内存限制 (MB)">
              <el-input-number
                v-model="localSettings.quickJsMemoryLimitMb"
                :min="1"
                :max="128"
                :step="1"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="执行整个脚本文件时 QuickJS 可分配的最大内存 (MB)">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
          <el-form-item label="脚本堆栈大小 (KB)">
              <el-input-number
                v-model="localSettings.quickJsStackSizeKb"
                :min="64"
                :max="1024"
                :step="64"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="执行整个脚本文件时 QuickJS 的最大调用堆栈大小 (KB)">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
          <el-form-item label="表达式内存限制 (MB)">
              <el-input-number
                v-model="localSettings.quickJsExprMemoryLimitMb"
                :min="1"
                :max="64"
                :step="1"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="评估单个表达式 (evaluateExpression) 时 QuickJS 可分配的最大内存 (MB)。建议低于脚本限制。">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
          <el-form-item label="表达式堆栈大小 (KB)">
              <el-input-number
                v-model="localSettings.quickJsExprStackSizeKb"
                :min="32"
                :max="512"
                :step="32"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="评估单个表达式 (evaluateExpression) 时 QuickJS 的最大调用堆栈大小 (KB)。建议低于脚本限制。">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
          
          <!-- --- ADD NEW Rich Display Settings --- -->
          <el-divider content-position="left">Rich Display (详情面板)</el-divider>
          <el-form-item label="集合/对象初始显示条数">
              <el-input-number
                v-model="localSettings.richDisplayItemLimit"
                :min="0"
                :max="50" 
                :step="1"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="在详情面板中，默认展开显示的对象属性、数组元素、Map/Set 条目的最大数量。">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
           <el-form-item label="最大递归显示深度">
              <el-input-number
                v-model="localSettings.richDisplayMaxDepth"
                :min="1"
                :max="10" 
                :step="1"
                controls-position="right"
                style="width: 120px;"
              />
              <el-tooltip placement="top" content="在详情面板中，递归显示嵌套对象/数组的最大层数，以防止过深或循环引用导致的性能问题。">
                 <el-icon class="setting-tooltip-icon"><InfoFilled /></el-icon>
              </el-tooltip>
          </el-form-item>
          <!-- --- END NEW Rich Display Settings --- -->

         </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetToDefaultSettings">重置为默认值</el-button>
        <el-button @click="resetToCurrentSettings">重置更改</el-button>
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="applySettings">
          应用更改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import {
  ElDialog, ElTabs, ElTabPane, ElForm, ElFormItem, ElRadioGroup, ElRadio,
  ElSlider, ElSelect, ElOption, ElSwitch, ElTooltip, ElIcon, ElButton, ElColorPicker, ElDivider, ElRadioButton, ElInputNumber
} from 'element-plus';
import { QuestionFilled, InfoFilled } from '@element-plus/icons-vue';
import {
  useUniversalVisualizerSettingsStore,
  type ColoringMode, type AttributeDisplayMode, type AttributeSeparatorStyle,
  type NodeRenderingMethod, type DagreAlign, type DagreRanker,
  type HandlePositionMode,
  type XmlTagNameDisplayMode,
  type XmlParserType,
  type ScriptParserEngine
} from '@/stores/universalVisualizerSettingsStore';
import { useUniversalEditorStore } from '@/stores/universalEditorStore';
import { defaultElementObjectColor } from '@/config'; // For color picker default

// --- Define Local Settings Interface (Add new fields) ---
interface LocalSettings {
  layoutDirection: 'TB' | 'LR';
  nodeSpacing: number;
  layerSpacing: number;
  dagreAlign: DagreAlign;
  dagreRanker: DagreRanker;
  handlePositionMode: HandlePositionMode;
  attributeDisplayMode: AttributeDisplayMode;
  attributeSeparatorStyle: AttributeSeparatorStyle;
  normalizeAppearanceWithAttrs: boolean;
  nodeRenderingMethod: NodeRenderingMethod;
  coloringMode: ColoringMode;
  singleStructureColorValue: string;
  trueSingleColorValue: string;
  xmlTagNameDisplayMode: XmlTagNameDisplayMode;
  selectedXmlParser: XmlParserType;
  enableRealtimeXmlValidation: boolean;
  enableAutomaticQuickJs: boolean;
  scriptParserEngine: ScriptParserEngine;
  wordWrap: boolean;
  quickJsMemoryLimitMb: number;
  quickJsStackSizeKb: number;
  quickJsExprMemoryLimitMb: number;
  quickJsExprStackSizeKb: number;
  showMiniMap: boolean;
  showControls: boolean;
  showBackground: boolean;
  richDisplayItemLimit: number;
  richDisplayMaxDepth: number;
}

// --- Props and Emits ---
const props = defineProps<{
  modelValue: boolean; // Controls dialog visibility (v-model)
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
}>();

// --- Store Access ---
const visualizerSettings = useUniversalVisualizerSettingsStore();
const editorStore = useUniversalEditorStore();

// --- Define Default Settings (Add new defaults) ---
const defaultSettings: Readonly<LocalSettings> = Object.freeze({
  layoutDirection: 'TB',
  nodeSpacing: 60,
  layerSpacing: 80,
  dagreAlign: undefined,
  dagreRanker: 'network-simplex',
  handlePositionMode: 'auto',
  attributeDisplayMode: 'all',
  attributeSeparatorStyle: 'dashed',
  normalizeAppearanceWithAttrs: true,
  nodeRenderingMethod: 'template',
  coloringMode: 'jdf-keyword-level',
  singleStructureColorValue: '#a7f3d0',
  trueSingleColorValue: '#d1d5db',
  xmlTagNameDisplayMode: 'nameOnly',
  selectedXmlParser: 'fast-xml',
  enableRealtimeXmlValidation: true,
  enableAutomaticQuickJs: true,
  scriptParserEngine: 'swc',
  wordWrap: false,
  quickJsMemoryLimitMb: 10,
  quickJsStackSizeKb: 512,
  quickJsExprMemoryLimitMb: 2,
  quickJsExprStackSizeKb: 128,
  showMiniMap: true,
  showControls: true,
  showBackground: true,
  richDisplayItemLimit: 10,
  richDisplayMaxDepth: 5,
});

// --- Local State --- (Initialize with correct types)
const activeTab = ref('layout');
// Use the interface when defining the reactive object
const localSettings = reactive<LocalSettings>({ ...defaultSettings });

// --- Watcher for True Single Color Value --- 
watch(() => localSettings.trueSingleColorValue, (newValue, oldValue) => {
  console.log(`[SettingsDialog] localSettings.trueSingleColorValue changed: ${oldValue} -> ${newValue}`);
});

// --- Methods ---
const initializeLocalSettings = () => {
  console.log("Dialog opened, initializing local settings from store.");
  // Assign values, types should now match
  localSettings.layoutDirection = visualizerSettings.layoutDirection;
  localSettings.nodeSpacing = visualizerSettings.nodeSpacing;
  localSettings.layerSpacing = visualizerSettings.layerSpacing;
  localSettings.dagreAlign = visualizerSettings.dagreAlign;
  localSettings.dagreRanker = visualizerSettings.dagreRanker;
  localSettings.handlePositionMode = visualizerSettings.handlePositionMode;
  localSettings.attributeDisplayMode = visualizerSettings.attributeDisplayMode;
  localSettings.attributeSeparatorStyle = visualizerSettings.attributeSeparatorStyle;
  localSettings.normalizeAppearanceWithAttrs = visualizerSettings.normalizeAppearanceWithAttrs;
  localSettings.nodeRenderingMethod = visualizerSettings.nodeRenderingMethod;
  localSettings.coloringMode = visualizerSettings.coloringMode;
  localSettings.singleStructureColorValue = visualizerSettings.singleStructureColorValue || defaultElementObjectColor;
  localSettings.trueSingleColorValue = visualizerSettings.trueSingleColorValue || '#d1d5db';
  localSettings.xmlTagNameDisplayMode = visualizerSettings.xmlTagNameDisplayMode;
  localSettings.selectedXmlParser = visualizerSettings.selectedXmlParser;
  localSettings.enableRealtimeXmlValidation = visualizerSettings.enableRealtimeXmlValidation;
  localSettings.enableAutomaticQuickJs = visualizerSettings.enableAutomaticQuickJs;
  localSettings.scriptParserEngine = visualizerSettings.scriptParserEngine;
  localSettings.wordWrap = visualizerSettings.wordWrap;
  localSettings.quickJsMemoryLimitMb = visualizerSettings.quickJsMemoryLimitMb;
  localSettings.quickJsStackSizeKb = visualizerSettings.quickJsStackSizeKb;
  localSettings.quickJsExprMemoryLimitMb = visualizerSettings.quickJsExprMemoryLimitMb;
  localSettings.quickJsExprStackSizeKb = visualizerSettings.quickJsExprStackSizeKb;
  localSettings.showMiniMap = visualizerSettings.showMiniMap;
  localSettings.showControls = visualizerSettings.showControls;
  localSettings.showBackground = visualizerSettings.showBackground;
  localSettings.richDisplayItemLimit = visualizerSettings.richDisplayItemLimit;
  localSettings.richDisplayMaxDepth = visualizerSettings.richDisplayMaxDepth;
};

const applySettings = () => {
  console.log("Applying settings from dialog to store:", localSettings);
  visualizerSettings.setLayoutDirection(localSettings.layoutDirection);
  visualizerSettings.setNodeSpacing(localSettings.nodeSpacing);
  visualizerSettings.setLayerSpacing(localSettings.layerSpacing);
  visualizerSettings.setDagreAlign(localSettings.dagreAlign);
  visualizerSettings.setDagreRanker(localSettings.dagreRanker);
  visualizerSettings.setHandlePositionMode(localSettings.handlePositionMode);
  visualizerSettings.setAttributeDisplayMode(localSettings.attributeDisplayMode);
  visualizerSettings.setAttributeSeparatorStyle(localSettings.attributeSeparatorStyle);
  visualizerSettings.setNormalizeAppearance(localSettings.normalizeAppearanceWithAttrs);
  visualizerSettings.setNodeRenderingMethod(localSettings.nodeRenderingMethod);
  visualizerSettings.setColoringMode(localSettings.coloringMode);
  visualizerSettings.setSingleStructureColorValue(localSettings.singleStructureColorValue);
  visualizerSettings.setTrueSingleColorValue(localSettings.trueSingleColorValue);
  visualizerSettings.setXmlTagNameDisplayMode(localSettings.xmlTagNameDisplayMode);
  visualizerSettings.setSelectedXmlParser(localSettings.selectedXmlParser);
  visualizerSettings.setEnableRealtimeXmlValidation(localSettings.enableRealtimeXmlValidation);
  visualizerSettings.setEnableAutomaticQuickJs(localSettings.enableAutomaticQuickJs);
  visualizerSettings.setScriptParserEngine(localSettings.scriptParserEngine);
  visualizerSettings.setWordWrap(localSettings.wordWrap);
  visualizerSettings.setQuickJsMemoryLimitMb(localSettings.quickJsMemoryLimitMb);
  visualizerSettings.setQuickJsStackSizeKb(localSettings.quickJsStackSizeKb);
  visualizerSettings.setQuickJsExprMemoryLimitMb(localSettings.quickJsExprMemoryLimitMb);
  visualizerSettings.setQuickJsExprStackSizeKb(localSettings.quickJsExprStackSizeKb);
  visualizerSettings.setShowMiniMap(localSettings.showMiniMap);
  visualizerSettings.setShowControls(localSettings.showControls);
  visualizerSettings.setShowBackground(localSettings.showBackground);
  visualizerSettings.setRichDisplayItemLimit(localSettings.richDisplayItemLimit);
  visualizerSettings.setRichDisplayMaxDepth(localSettings.richDisplayMaxDepth);
  editorStore.redoLayout();
  closeDialog();
};

// RENAMED: Reset to current store values
const resetToCurrentSettings = () => {
  console.log("Resetting local settings to current store values.");
  initializeLocalSettings(); // Re-initialize from store
};

// NEW: Reset to application defaults
const resetToDefaultSettings = () => {
  console.log("Resetting local settings to application defaults.");
  Object.assign(localSettings, defaultSettings);
};

const closeDialog = () => {
  emit('update:modelValue', false);
};

// Watch for external changes to store and update local state if dialog is open?
// Could be complex, maybe reset on open is enough for now.
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    initializeLocalSettings();
  }
});

// Initialize on component setup as well
initializeLocalSettings();

</script>

<style lang="scss" scoped>
.settings-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}

.settings-tabs {
  min-height: 300px; // Ensure tabs have some height
}

/* Styles for the Flexbox radio group in Coloring Tab */
.coloring-mode-radio-group-flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 20px; // Row gap, column gap

  .radio-item-wrapper {
    flex-basis: calc(50% - 10px); // Adjust basis for gap
    box-sizing: border-box;
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;

    .el-radio {
      margin-right: 0; // Remove default margin
      white-space: nowrap; // Prevent radio label wrapping
    }

    .mode-color-picker {
      flex-shrink: 0;
      margin-left: auto; // Push picker to the right if needed
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-radio-group {
  margin-right: 10px; // Add some space before tooltip if needed
}

.setting-tooltip-icon {
    margin-left: 8px;
    color: var(--el-text-color-secondary);
    cursor: help;
}

/* Ensure switch and tooltip align nicely */
.el-form-item__content {
  .el-switch {
    margin-right: 5px; /* Adjust spacing if needed */
  }
}
</style>